Ext.define('Service.module.controller.ModuleController', {
	extend: 'WebOs.ex.DefaultController',
	
	moduleName : 'Service_module',
	
	views : [
		'Service.module.view.InitContainer',
		'Service.module.view.ModuleTree',
		'Service.module.view.ModuleView',
		'Service.module.view.ModuleActionGrid',
		'Service.module.view.ModuleAddWindow',
		'Service.module.view.ModuleAddForm',
		'Service.module.view.ModuleChgWindow',
		'Service.module.view.ModuleChgForm'
	],
	
	stores : [
		'Service.module.store.ModuleTypeStore',
		'Service.module.store.ActionDataListStore'
	],
	
	models : [
		'Service.module.model.ModuleModel'
	],
	
	refs : [
		{ref : 'moduleWindow', selector : 'Service_module_view_InitContainer'},
		{ref : 'moduleTree', selector : 'Service_module_view_ModuleTree'},
		{ref : 'moduleView', selector : 'Service_module_view_ModuleView'},
		{ref : 'moduleActionGrid', selector : 'Service_module_view_ModuleActionGrid'},
		{ref : 'moduleContainer', selector : 'container[id=Service_module_view_Container]'},
		{ref : 'moduleAddWindow', selector : 'Service_module_view_ModuleAddWindow'},
		{ref : 'moduleAddForm', selector : 'Service_module_view_ModuleAddForm'},
		{ref : 'moduleChgWindow', selector : 'Service_module_view_ModuleChgWindow'},
		{ref : 'moduleChgForm', selector : 'Service_module_view_ModuleChgForm'}
	],
	
	

	init: function(app,config) {
		var me=this;
		var me = this;
		me.app = app;
		Ext.apply(me, config);
        this.control({
        	'Service_module_view_InitContainer' : {
        		beforerender : me.initModulesData
        	},
        	'Service_module_view_ModuleAddWindow' : {
        		beforeclose : me.onConfirmWindowBeforeClose
        	},
        	'Service_module_view_ModuleChgWindow' : {
        		beforeclose : me.onConfirmWindowBeforeClose
        	},
        	'Service_module_view_ModuleTree' : {
        		itemclick : me.onTreeNodeClick
        	},
        	'menuitem[action=showModuleAddWindow]' : {
        		click : me.onShowModuleAddWindow
        	},
        	'menuitem[action=showModuleChgWindow]' : {
        		click : me.onShowModuleChgWindow
        	},
        	'menuitem[module=module][action=delModule]' : {
        		click : me.onBtnDelModule
        	},
        	'menuitem[module=module][action=stopModule]' : {
        		click : me.onBtnStopModule
        	},
        	'menuitem[module=module][action=startModule]' : {
        		click : me.onBtnStartModule
        	},
        	'button[module=module][action=addModule]' : {
        		click : me.onBtnAddModule
        	},
        	'button[module=module][action=cancelModuleAddForm]' : {
        		click : me.onBtnCancelWindow
        	},
        	'button[module=module][action=cancelModuleChgForm]' : {
        		click : me.onBtnCancelWindow
        	},
        	'button[module=module][action=chgModule]' : {
        		click : me.onBtnChgModule
        	},
        	'button[module=module][action=saveActions]' : {
        		click : me.onBtnSaveActions
        	}
        });
    },
    
    
    initModulesData : function(){
    	var me = this;
    	me.request({
    		params : {
    			'module' : me.moduleName,
    			'action' : 'getAllModules'
    		},
    		onSuccess : function(rs,opts,btn){
    			var result = rs.result;
    			me.setModuleTreeData(result);
    		}
    	});
    },
    
    setModuleTreeData : function(datas){
    	var me = this;
    	var treeNodes = me.getTreeDataByPname('root',datas);
    	var root = {
    		text : '组织结构',
    		leaf : false,
    		id : 1,
    		moduleType : 1,
    		moduleText : '根模块',
    		moduleName : 'root',
    		validFlag : 1,
    		children : treeNodes || []
    	};
    	
    	var tree = me.getModuleTree();
    	tree.getStore().setRootNode(root);
    	tree.expandAll();
    	
    },
    
    getChildrenDatasByPname : function(pname,datas) {
		var me = this, ret = [];
		Ext.each(datas,function(data,index,self) {
			var parent = data['pname'];
			if (parent == pname)
				ret.push(data);
		}, me);
		return ret;
	},
	
    getTreeDataByPname : function(pname,datas) {
    	if(datas==null || datas.length==0)
    		return null;
		var me = this, children = [];
		var recs = me.getChildrenDatasByPname(pname,datas);
		
		for (var p in recs) {
			var rec = recs[p];
			var tmpmoduleType = rec['moduleType'];
			var isFolder = tmpmoduleType == 1 ? true: false;
			var icons = core.getActiveView().configure.getIcons(rec['moduleName'],isFolder);
			var tmpbigIcon = icons['large'],tmpsmallIcon=icons['small'];
			var treeNode = {
				text : rec['moduleText'],
				id : rec['id'],
				moduleType : tmpmoduleType,
				sortIndex : rec['sortIndex'],
				moduleText : rec['moduleText'],
				moduleName : rec['moduleName'],
				codePath : rec['codePath'],
				tableName : rec['tableName'],
				pname : rec['pname'],
				remark : rec['remark'],
				bigIcon : tmpbigIcon,
				smallIcon : tmpsmallIcon,
				serviceName : rec['serviceName'],
				serviceCls : rec['serviceCls'],
				validFlag : rec['validFlag']
			};
			if (rec['moduleType'] == 2) {
				treeNode['leaf'] = true;
				children.push(treeNode);
			} else if (rec['moduleType'] == 1) {
				treeNode['leaf'] = false;
				treeNode['children'] = me.getTreeDataByPname(rec['moduleName'],datas);
				children.push(treeNode);
			}
			if(rec['validFlag'] != 1){
				if(rec['moduleType'] == 1)
					treeNode.iconCls = 'x-tree-icon-parent-invalid';
				else if(rec['moduleType'] == 2)
					treeNode.iconCls = 'x-tree-icon-leaf-invalid';
			}
		}
		return children;
	},
    
	onTreeNodeClick : function(view,rec,item,index,e,opts){
		var me = this;
		var moduleType = rec.get('moduleType');
		var container = me.getModuleContainer();
		var cardLayout = container.getLayout();
		
		if(moduleType == 1){//如果是目录则切换到view，并显示模块内容
			var records = rec.childNodes;
			var dataView = me.getModuleView();
			cardLayout.setActiveItem(dataView);
			dataView.setStoreDatas(rec,records);
		}else if(moduleType == 2){//如果是模块则切换到grid，显示action内容
			var dataGrid = me.getModuleActionGrid();
			cardLayout.setActiveItem(dataGrid);
			dataGrid.loadData({
				'moduleId' : rec.get('id'),
				'moduleText' : rec.get('moduleText')
			});
		}
	},
    
	onShowModuleAddWindow : function(item,e,opts){
		var me = this;
		var view = me.getModuleView();
		var rec = view.getParentRecord();
		if(rec){
			var moduleAddWindow = new Service.module.view.ModuleAddWindow();
			moduleAddWindow.show();
			var form = me.getModuleAddForm().getForm();
			form.setValues({
				pname : rec.get('moduleName'),
				parentText : rec.get('moduleText')
			});
		}else{
			ShowInfoMsg('添加模块','请从左侧树中选择需要维护的父模块');
		}
	},
	
	onShowModuleChgWindow : function(item,e,opts){
		var me = this;
		var htmlEl = e.getTarget();
		var view = me.getModuleView();
		var rec = view.getSelectedRecord();
		if(rec){
			var moduleChgWindow = new Service.module.view.ModuleChgWindow();
			moduleChgWindow.show();
			var form = me.getModuleChgForm().getForm();
			var serviceCls = rec.data['serviceCls'].substring(rec.data['serviceCls'].lastIndexOf('.')+1,rec.data['serviceCls'].length);
			var clone = Ext.clone(rec.data);
			clone['serviceCls'] = serviceCls;
			form.setValues(clone);
		}else{
			ShowInfoMsg('修改模块','请选择要修改的模块');
		}
	},
	
    onBtnAddModule : function(btn,evt,opts){
    	var me=this;
    	var addForm = me.getModuleAddForm();
    	var valid = addForm.getForm().isValid();
    	if(!valid){
    		ShowErrorMsg("模块信息验证失败","模块信息不合法，请检查后提交");
    	}else{
    		me.saveNewModule(btn,addForm);
    	}
    },
    
    onBtnChgModule : function(btn,evt,opts){
    	var me = this;
    	var chgForm = me.getModuleChgForm();
    	var valid = chgForm.getForm().isValid();
    	if(!valid){
    		ShowErrorMsg("模块信息验证失败","模块信息不合法，请检查后提交");
    	}else{
    		me.saveChgModule(btn,chgForm);
    	}
    },
    
    onBtnDelModule : function(btn,evt,opts){
    	var me = this;
    	Ext.MessageBox.show({
    		title : '操作提示',
    		msg : '模块被删除后，对应的权限及Action将被同时删除，且无法恢复，是否继续？',
    		width : 200,
    		buttons : Ext.MessageBox.OKCANCEL,
    		icon : Ext.MessageBox.WARNING,
    		fn : me.onDelModuleConfirm,
    		scope : this
    	});
    },
    
    onBtnStartModule : function(btn,evt,opts){
    	var me = this;
    	Ext.MessageBox.show({
    		title : '操作提示',
    		msg : '启用模块，其上级模块将被自动启用，是否确认启用？',
    		width : 200,
    		buttons : Ext.MessageBox.OKCANCEL,
    		icon : Ext.MessageBox.WARNING,
    		fn : function(buttonId){
    			if(buttonId == 'ok'){
    				var selectedRecord = me.getModuleView().getSelectedRecord();
    				if(selectedRecord){
    					me.startModule(selectedRecord);
    				}
    			}
    		},
    		scope : this
    	});
    },
    
    onBtnStopModule : function(btn,evt,opts){
    	var me = this;
    	Ext.MessageBox.show({
    		title : '操作提示',
    		msg : '停用模块，此模块包含的子模块也将被停用，请确认是否继续？',
    		width : 200,
    		buttons : Ext.MessageBox.OKCANCEL,
    		icon : Ext.MessageBox.WARNING,
    		fn : function(buttonId){
    			if(buttonId == 'ok'){
    				var selectedRecord = me.getModuleView().getSelectedRecord();
    				if(selectedRecord){
    					me.stopModule(selectedRecord);
    				}
    			}
    		},
    		scope : this
    	});
    },
    
    onBtnSaveActions : function(btn,evt,opts){
        var me = this;
        var grid = me.getModuleActionGrid();
        var recs = grid.getStore().getModifiedRecords();
        var drecs = grid.getStore().getRemovedRecords();
        if(recs.length==0 && drecs.length==0)
        	return;
        me.saveActions(recs,drecs,btn,grid);
    },
    
    saveActions : function(recs,drecs,btn,grid){
    	var me = this;
    	var datas = [];
    	var deldatas = [];
    	Ext.Array.each(recs,function(rec,index,self){
    		rec.set('moduleId',grid['moduleId']);
    		datas[index] = rec.getData();
    	},me);
    	Ext.Array.each(drecs,function(rec,index,self){
    		deldatas[index] = rec.get('id');
    	},me);
    	datas = Ext.JSON.encode(datas);
    	var rparams = {
			'module': me.moduleName,
			'action': btn.action,
			'actions' : datas,
			'delActionIds' : deldatas
		};
    	me.request({
    		masker : me.getModuleWindow(),
			params : rparams,
			scope : me,
			onSuccess : function(rs,opts){
				var grid = me.getModuleActionGrid();
				grid.getStore().load();
				ShowInfoMsg('操作提示','Action保存成功');
			}
    	});
    },
    
    startModule : function(rec){
    	var me = this;
    	var rparams = {
			'module':me.moduleName,
			'action':'startModule'
		};
		
		Ext.applyIf(rparams,rec.data);
		
    	if(rec){
    		var tree = me.getModuleTree();
    		me.request({
    			masker : me.getModuleWindow(),
    			params : rparams,
    			scope : me,
    			onSuccess : function(rs,opts){
    				tree.startModule(rec);
    				ShowInfoMsg('操作提示','模块启用成功');
    			}
    		});
    	}
    },
    
    stopModule : function(rec){
    	var me = this;
    	var rparams = {
			'module':me.moduleName,
			'action':'stopModule'
		};
		
		Ext.applyIf(rparams,rec.data);
		
    	if(rec){
    		var tree = me.getModuleTree();
    		me.request({
    			masker : me.getModuleWindow(),
    			params : rparams,
    			scope : me,
    			onSuccess : function(rs,opts){
    				tree.stopModule(rec);
    				ShowInfoMsg('操作提示','模块停用成功');
    			}
    		});
    	}
    },
    
    onDelModuleConfirm : function(buttonId){
    	var me=this;
    	if(buttonId == 'ok'){
			var view = me.getModuleView();
			var rec = view.getSelectedRecord();
			if(rec){
				if(rec.get('moduleType') == 1){
					var id = rec.get('id');
					var moduleTree = me.getModuleTree();
					var node = moduleTree.getStore().getNodeById(rec.get('id'));
					if(node.hasChildNodes()){
						ShowWarningMsg('操作失败提示','模块包含子模块，不允许删除');
						return;
					}
				}
				me.delModule(rec);
			}else{
				ShowInfoMsg('操作提示','请选择要删除的模块');
			}
    	}
    },
    
    delModule : function(rec){
    	var me = this;
    	if(rec){
    		me.request({
    			masker : me.getModuleWindow(),
    			params : {
    				'id':rec.get('id'),
    				'moduleType' : rec.get('moduleType'),
    				'module':me.moduleName,
    				'action':'delModule'
    			},
    			scope : me,
    			onSuccess : function(rs,opts){
    				var tree = me.getModuleTree();
    				tree.delNode(rec);
    				var view = me.getModuleView();
    				view.delModule(rec);
    				ShowInfoMsg('操作提示','模块删除成功');
    			}
    		});
    	}
    },
    
    saveNewModule : function(btn,form){
    	var me = this;
    	var params = form.getForm().getValues();
    	params['serviceCls'] = 'Service.' + params['codePath'] + '.'  +params['serviceCls'] 
    	var view = me.getModuleView();
    	var tree = me.getModuleTree();
    	var parentRecord = view.getParentRecord();
    	Ext.apply(params,{
    		'module' : me.moduleName,
    		'action' : btn.action,
    		'validFlag' : parentRecord.get('validFlag')
    	});
    	me.request({
    		params : params,
    		scope : me,
    		masker : me.getModuleAddWindow(),
    		onSuccess : function(rs,opts,btn){
    			var data = rs.result;//获取返回的模块信息ID
    			var model = new Service.module.model.ModuleModel(data);
    			view.addModule(model);
    			
    			tree.addChildNode(model);
    			ShowInfoMsg('操作提示','模块添加成功');
    		}
    	});
    },
    
    saveChgModule : function(btn,form){
    	var me = this;
    	var params = form.getForm().getValues();
    	params['serviceCls'] = 'Service.' + params['codePath'] + '.'  +params['serviceCls']; 
    	Ext.apply(params,{
    		'module' : me.moduleName,
    		'action' : btn.action
    	});
    	me.request({
    		params : params,
    		scope : me,
    		masker : me.getModuleChgWindow(),
    		onSuccess : function(rs,opts,btn){
    			var data = rs.result;//获取返回的模块信息ID
    			var model = new Service.module.model.ModuleModel(params);
    			me.getModuleTree().chgNode(model);
    			ShowInfoMsg('操作提示','模块修改成功');
    			me.getModuleChgWindow().destroy();
    		}
    	});
    }
});
